<template>
  <a-layout class="allLayout">
    <a-layout-content>
      <unit-table
      :columns="this.isManager?this.$staticMenu.newPageColumns:this.$staticMenu.newPageNoActionColumns"
      :url="tableUrl"
      :type="tableType"
      selectType="checkbox"
      :params="tableParams"
      :size="pageSize"
      :sizeOptions="pageSizeOptions"
      :selectedKeys="tableSelectedKeys"
      rowKeyName="id"
      ref="unitTable"
      @onSelect="tableOnSelect"
      >
      <a-row slot="searchCri">
        <a-col :span="3">
          <a-input v-model="tableParams.fileName" class="searchCriteria" @keydown.native="keydown($event)" placeholder="文件名称" />
        </a-col>
        <a-col :span="3">
          <a-select
            v-model="tableParams.status"
            class="searchCriteria"
              v-if="this.isManager"
          >
            <a-select-option v-for="(item, key) of fileStatus"
                             :key='item.value'
                             :value="item.value"
            >{{ item.label }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="18" style="text-align: right;">
          <a-button type="primary" @click="criteriaSearch">
            <a-icon type="search"/>
            查询
          </a-button>
          <a-button @click="clearCriteria">
            <a-icon type="sync"/>
            </i>重置
          </a-button>
        </a-col>
      </a-row>
        <!-- 补充表格操作 -->
        <div slot='tableAct' class="actionBtn">
          <a-button type="primary" @click="importFile">
            <a-icon type="import" />导入
          </a-button>
         <span style="float:right"  v-if="this.isManager&&approved=='未审批'">
          <a-button type="primary" class="btn-success" @click="acceptAll">
            <a-icon type="check" />审批通过
          </a-button>
          <a-button type="danger" @click="rejectAll">
            <a-icon type="close" />拒绝
          </a-button>
        </span>
        </div>
        <!-- end -->
      <!-- 补充表格每行的操作 -->
      <span slot="statusSwitch" slot-scope="props">
        <span v-if="props.record.status=='审批通过'" class="text-success">{{props.record.status}}</span>
        <span v-if="props.record.status=='审批拒绝'" class="text-danger">{{props.record.status}}</span>
        <span v-if="props.record.status=='未审批'">{{props.record.status}}</span>
      </span>
      <!-- 补充表格每行的操作 -->
      <span slot="tableRowAct" slot-scope="props">
        <!-- <a-divider type="vertical" v-if="props.record.status=='未审批'" /> -->
        <a @click="update(props.record)" v-if="props.record.status=='未审批'">
          <span class="ant-tag ant-tag-blue">
            <a-icon type="cloud-sync" />更新
          </span>
        </a>
        <!-- <a-divider type="vertical" v-if="props.record.status=='未审批'" /> -->
        <a v-if="props.record.status=='未审批'" @click="accept(props.record)">
          <span class="ant-tag ant-tag-green">
            <a-icon type="check" />审批通过
          </span>
        </a>
        <!-- <a-divider type="vertical" v-if="props.record.status=='未审批'" /> -->
        <a v-if="props.record.status=='未审批'" @click="reject(props.record)">
          <span class="ant-tag ant-tag-volcano">
            <a-icon type="close" />拒绝
          </span>
        </a>
        <!-- <a-divider type="vertical" /> -->
        <a @click="deletefile(props.record)">
          <span class="ant-tag ant-tag-volcano">
            <a-icon type="close" />删除
          </span>
        </a>
      </span>
      </unit-table>
        <modal
          ref="importModalForm"
          :title="modalTitle"
          :visible="modalVisible"
          @ok="handleOk"
          @cancel="handleCancel"
          :type="opType"
          :param="uploadParam"
          :validator="validatorForm"
          :action="fileAction"
        ></modal>
    </a-layout-content>
  </a-layout>
</template>

<script>
  import {GETALLLIST,GETALLACCEPTLIST,APPROVALACCEPT,APPROVALDLETE,APPROVALREJECT,  UPLOADFILE,UPLOADFILEUPDATE,GETALLSTATUS} from '@/../static/js/apis.js'
  import unitTable from "@/common/table"
  import modal from './components/newPageModal';
  import moment from 'moment';
  import global from "@/../static/global.vue"
  import { importForm, importForm1 } from '@/../static/js/formValidators.js';
  export default {
    inject: ['reload'], // 注入App里的reload方法
    name: 'approval',
    components: {
      unitTable,
      modal
    },
    data() {
      return {
        tableSelectedKeys: [],
        //tableUrl: GETALLLIST.url,  //调用表格组件，必须参数，后台数据接口
        tableType: GETALLLIST.type,  //调用表格组件，必须参数，后台方法方法（get，post）
        pageSize: 15,
        pageSizeOptions: ['15', '20', '40'],
        modalTitle: '', // modal标题
        modalVisible: false, // modal关闭打开控制器
        fileStatus: [],
        tableParams: {
          fileName: '',
          status: '全部审批状态',
          menuId:this.$route.query.menuId
        },
        approved: '',
        opType: '',
        uploadParam: {},
        fileAction: '', // 导入文件提交路径
        validatorForm: importForm,
        userId: parseInt(localStorage.getItem('userid'))
      }
    },
   watch:{
      $route(to,from){
        this.tableParams.menuId=to.query.menuId
        this.$refs.unitTable.fetch(1)
      }
   },
   computed: {
      // 判断是否管理员
      isManager() {
        return global.isManager(global.SYS_DATA_MANAGE)
      },
      tableUrl () {
        return global.isManager(global.SYS_DATA_MANAGE)
          ? GETALLLIST.url
          : GETALLACCEPTLIST.url
      }
    },
    methods: {
      keydown(e){
        if(e.keyCode==32){
          e.returnValue=false
        }
      },
      /*获取静态数据*/
       getStaticData() {
        let self = this
        GETALLSTATUS('', function (res) {
          self.fileStatus = res.obj
        })
      },
      criteriaSearch () {
        this.approved = this.tableParams.status
        this.$refs.unitTable.fetch(1)
      },
            /*重置按钮*/
      clearCriteria() {
        this.tableParams.fileName = ''
        this.tableParams.status = '全部审批状态'
        this.$refs.unitTable.rowSelection.onChange([ ],[ ])
        this.criteriaSearch()
      },
      /*表格checkbox选中事件*/
      tableOnSelect(selectedRowKeys, selectedRows) {
        this.tableSelectedKeys = selectedRowKeys
      },
       /* modal确定事件 */
      handleOk(e) {
        this.modalVisible = false
      },
      /* modal取消事件 */
      handleCancel(e) {
        this.modalVisible = false
      },
      importFile() {
        this.modalTitle = '导入文件';
        this.modalVisible = true;
        this.opType = '新建';
        this.fileAction = UPLOADFILE.url
        this.uploadParam = {
          userId: this.userId
        }
        this.validatorForm = importForm
      },
     acceptAll() {
        let self = this
        const selectedRowKeys = self.tableSelectedKeys
        var param = {
          ids: selectedRowKeys,
          userId: this.userId
        }
        if (selectedRowKeys.length > 0) {
          APPROVALACCEPT(param, function (res) {
            self.$message.success(res.message)
            self.reload()

          })
        } else {
          self.$message.warning("请在表格中勾选要审批的数据！")
        }
      },
      rejectAll() {
        let self = this
        const selectedRowKeys = self.tableSelectedKeys
        var param = {
          ids: selectedRowKeys,
          userId: this.userId
        }
        if (selectedRowKeys.length > 0) {
          APPROVALREJECT(param, function (res) {
            self.$message.success(res.message)
            self.reload()
          })
        } else {
          self.$message.warning("请在表格中勾选要审批的数据！")
        }
      },
      update(record) {
        this.opType = '更新';
        this.modalTitle = record.fileName
        this.modalVisible = true
        this.fileAction = UPLOADFILEUPDATE.url
        this.uploadParam = {
          userId: this.userId,
          fileId: record.id
        }
        this.validatorForm = importForm1
        // form的setFieldsValue方法放入参数与form中对应，可少不可多，用以下方法进行筛选
        const pickArr = ['fileConfig', 'fileTime', 'gcs','lan','lon','scale','regionList','scanLevel']
        const formShowInfo = _.pick(record, pickArr)
        formShowInfo.fileTime = moment(formShowInfo.fileTime, 'YYYY-MM-DD')
        // 把数据放入modal，要在form加载完成后
        this.$nextTick(() => {
          this.$refs.importModalForm.form.setFieldsValue(formShowInfo)
        })
      },
        accept(record) {
            let self = this
            var param = {
              ids: [record.id],
              userId: parseInt(localStorage.getItem('userid'))
            }
            this.$confirm({
                title: '确定要通过该项吗?',
                content: '',
                onOk () {
                  APPROVALACCEPT(param, function (res) {
                    self.$message.success(res.message)
                    self.reload()
                  })
                }
              })

          },

          deletefile(record) {
            let self = this
            var param = {
              ids: [record.id],
              userId: parseInt(localStorage.getItem('userid'))
            }

            this.$confirm({
              title: '确定要删除该项吗?',
              content: '',
              onOk () {
                APPROVALDLETE(param, function (res) {
                  self.$message.success(res.message)
                  self.reload()
                })
              }
            })
          },

          reject(record) {
            let self = this
            var param = {
              ids: [record.id],
              userId: parseInt(localStorage.getItem('userid'))
            }
          this.$confirm({
              title: '确定要拒绝该项吗?',
              content: '',
              onOk () {
                APPROVALREJECT(param, function (res) {
                  self.$message.success(res.message)
                  self.reload()
                })
              }
            })

          }
    },
    created() {
      this.getStaticData()
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .allLayout {
    margin: 30px;
  }

  .ant-layout-content {
    background-color: white;
  }
  .searchCriteria {
    width: 80%;
  }
  .actionBtn button:not(:last-child),
  .ant-row button:not(:last-child) {
    margin-right: 20px;
  }

  .action {
    color: #1890ff
  }
  .ant-tag {
  margin: 5px;
}
</style>
